extends Node

# 信号
signal dialogue_ended
signal dialogue_line_changed(current_line: int, total_lines: int)

# 对话数据
var current_dialogue: Array[Dictionary] = []
var current_line: int = 0
var is_dialogue_active: bool = false
var npc_portrait: Texture2D
var npc_name: String = ""

# 自动播放设置
var auto_advance_time: float = 5.0  # 5秒自动跳转
var auto_timer: Timer

# UI引用
var dialogue_ui: Control
var canvas_layer: CanvasLayer

func _ready():
	# 创建自动播放计时器
	auto_timer = Timer.new()
	auto_timer.wait_time = auto_advance_time
	auto_timer.timeout.connect(_on_auto_advance)
	auto_timer.one_shot = true
	add_child(auto_timer)
	
	# 创建UI层
	create_dialogue_ui()

func _input(event):
	"""处理输入事件"""
	if is_dialogue_active and event.is_action_pressed("ui_accept"):
		next_line()

func start_dialogue(dialogue_data: Array[Dictionary], portrait: Texture2D = null, speaker_name: String = ""):
	"""开始对话"""
	if is_dialogue_active:
		return
	
	current_dialogue = dialogue_data
	npc_portrait = portrait
	npc_name = speaker_name
	current_line = 0
	is_dialogue_active = true
	
	# 显示对话UI
	if dialogue_ui:
		dialogue_ui.show_dialogue()
	
	# 显示第一行对话
	show_current_line()
	
	# 暂停游戏中的玩家移动
	var player = get_tree().get_first_node_in_group("player")
	if player and player.has_method("set_can_move"):
		player.set_can_move(false)

func next_line():
	"""显示下一行对话"""
	if not is_dialogue_active:
		return
	
	# 停止自动播放计时器
	auto_timer.stop()
	
	current_line += 1
	
	if current_line >= current_dialogue.size():
		# 对话结束
		end_dialogue()
	else:
		# 显示下一行
		show_current_line()

func show_current_line():
	"""显示当前行对话"""
	if current_line >= current_dialogue.size():
		return
	
	var line_data = current_dialogue[current_line]
	var speaker = line_data.get("speaker", "")
	var text = line_data.get("text", "")
	
	# 更新UI
	if dialogue_ui:
		dialogue_ui.update_dialogue(speaker, text, npc_portrait, npc_name)
	
	# 发送信号
	dialogue_line_changed.emit(current_line, current_dialogue.size())
	
	# 启动自动播放计时器
	auto_timer.start()

func end_dialogue():
	"""结束对话"""
	if not is_dialogue_active:
		return
	
	is_dialogue_active = false
	auto_timer.stop()
	
	# 隐藏对话UI
	if dialogue_ui:
		dialogue_ui.hide_dialogue()
	
	# 恢复玩家移动
	var player = get_tree().get_first_node_in_group("player")
	if player and player.has_method("set_can_move"):
		player.set_can_move(true)
	
	# 发送对话结束信号
	dialogue_ended.emit()

func _on_auto_advance():
	"""自动播放下一行"""
	next_line()

func create_dialogue_ui():
	"""创建对话UI"""
	# 创建CanvasLayer
	canvas_layer = CanvasLayer.new()
	get_tree().root.call_deferred("add_child", canvas_layer)
	
	# 延迟加载并实例化对话UI
	call_deferred("_setup_dialogue_ui")

func _setup_dialogue_ui():
	"""延迟设置对话UI"""
	var dialogue_ui_scene = load("res://ui/dialogue_ui.tscn")
	if dialogue_ui_scene:
		dialogue_ui = dialogue_ui_scene.instantiate()
		canvas_layer.call_deferred("add_child", dialogue_ui)
	else:
		print("错误：无法加载对话UI场景")

func set_auto_advance_time(time: float):
	"""设置自动播放时间"""
	auto_advance_time = time
	auto_timer.wait_time = time
